package com.htthorizon.powersupply.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.htthorizon.powersupply.domain.AdsCstCjbdConsVoltloweDi;
import com.htthorizon.powersupply.domain.RdsGridTgCurDf;
import com.htthorizon.powersupply.domain.RdsGridTgPowerDf;
import com.htthorizon.powersupply.domain.RdsGridTgVoltDf;
import com.htthorizon.powersupply.domain.RealTimePowerOutage;
import com.htthorizon.powersupply.domain.RealTimePowerOutageUser;
import com.htthorizon.powersupply.dto.LineLoad;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Brilliant
 */
@Component
@Slf4j
public class ApiUtil {

    /**
     * post_源网荷储_春节保电_台区实时功率_tgPower_按台区查询_测试
     */
//    String REAL_TIME_POWER_TEST = "http://ds-server.ops.sgmc.sgcc.com.cn/dataapi/496107061341113";
    String REAL_TIME_POWER_TEST = "http://ds-server.ops.sgmc.sgcc.com.cn/dataapi/496107061341033";

    /**
     * post_源网荷储_春节保电_台区实时电压_tgVolt_按台区查询_测试:cst/cjbd/rds/post_tg_volt_96_df_htlx_test
     */
//    String REAL_TIME_POWER_VOLT_TEST = "http://ds-server.ops.sgmc.sgcc.com.cn/dataapi/496107061341114";
    String REAL_TIME_POWER_VOLT_TEST = "http://ds-server.ops.sgmc.sgcc.com.cn/dataapi/496107061341071";


    /**
     * post_源网荷储_春节保电_台区实时电流_tgCur_按台区查询_测试
     */
//    String REAL_TIME_CUR_VOLT = "http://ds-server.ops.sgmc.sgcc.com.cn/dataapi/496107061341111";
    String REAL_TIME_CUR_VOLT = "http://ds-server.ops.sgmc.sgcc.com.cn/dataapi/496107061341072";


    /**
     * post_源网荷储_春节保电_用户低电压_consVoltlowe_按用户查询_测试
     */
    String ads_cst_cjbd_cons_voltlowe_di = "http://ds-server.ops.sgmc.sgcc.com.cn/dataapi/496107061341115";

    /**
     * 实时停电台区
     */
    String REAL_TIME_POWER_OUTAGE = "http://e79d5911a55048cb83c6bc8eba835782.apigateway.res.sgmc.sgcc.com.cn/CST/LDJSC/ADB/GET_ADS_CST_HYGSZDBB_DATASHAREQUEUE_METEREVENT_DATA_LINE_NO_INFO";

    /**
     * 实时停电用户
     */
    String REAL_TIME_POWER_OUTEAGE_USER = "http://e79d5911a55048cb83c6bc8eba835782.apigateway.res.sgmc.sgcc.com.cn/CST/LDJSC/ADB/GET_ADS_CST_HYGSZDBB_DATASHAREQUEUE_METEREVENT_DATA_USER_TG_NO";

    /**
     * 用户低电压数据
     */
    String USER_LOW_VOLTAGE_DATA = "http://ds-server.ops.sgmc.sgcc.com.cn/dataapi/496107061341017";


    /**
     *
     * 线路重过载
     * 与其他返回结果不同 且少于2000
     */
    String LINE_LOAD="http://25.212.174.188:10180/api/server/data/live/line";


    public static void main(String[] args) {
        String str="{\n" +
                "    \"code\": 0,\n" +
                "    \"data\": {\n" +
                "        \"data\": [\n" +
                "            {\n" +
                "                \"busbar_id\": \"115404742179422594\",\n" +
                "                \"busbar_nm\": \"株洲.横店村/10kV.10kVⅠ母\",\n" +
                "                \"busbarid\": \"115404742179422594\",\n" +
                "                \"i0\": 0,\n" +
                "                \"ia\": \"-\",\n" +
                "                \"ib\": \"100.8373\",\n" +
                "                \"ic\": \"100.2158\",\n" +
                "                \"line_id\": \"PD_10000100_515361\",\n" +
                "                \"line_nm\": \"横竹线326\",\n" +
                "                \"p\": \"1.7160\",\n" +
                "                \"substation_id\": \"113997367295869311\",\n" +
                "                \"substation_nm\": \"株洲.横店村\",\n" +
                "                \"timestamp\": \"2025-01-22 10:07:26\",\n" +
                "                \"uab\": \"-\",\n" +
                "                \"wg_power\": \"0.5642\"\n" +
                "            }]}}";

        JSONObject jsonObject = JSONObject.parseObject(str);
        Object o = jsonObject.get("code");
        System.out.println(o);
        JSONObject data = jsonObject.getJSONObject("data");
            JSONArray list = data.getJSONArray("data");
            System.out.println(list);


    }


    public List<LineLoad> getLineLoad(String pageNum, String pageSize) throws URISyntaxException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        URIBuilder uri = new URIBuilder(LINE_LOAD);
        HttpGet httpGet = new HttpGet(uri.build());
        CloseableHttpResponse response = httpClient.execute(httpGet);
        String str = EntityUtils.toString(response.getEntity(), "UTF-8");
        JSONObject result = JSONObject.parseObject(str);
        try{
            JSONObject data = result.getJSONObject("data");
            JSONArray list = data.getJSONArray("data");
            return list.toJavaList(LineLoad.class);
        }catch (Exception e){
            log.error("getLineLoad error", e);
            return new ArrayList<>();
        }



    }



    public List<AdsCstCjbdConsVoltloweDi> getAdsCstCjbdConsVoltloweDi(String pageNum, String pageSize) throws URISyntaxException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = getCommonHttpPost(pageNum, pageSize, USER_LOW_VOLTAGE_DATA);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        try {
            return this.parseData(EntityUtils.toString(entity, "UTF-8"), AdsCstCjbdConsVoltloweDi.class);
        } catch (Exception e) {
            log.error("AdsCstCjbdConsVoltloweDi error", e);
            return new ArrayList<>();
        } finally {
            response.close();
            httpClient.close();
        }
    }

    public Integer getAdsCstCjbdConsVoltloweDiTotalNum(String pageNum, String pageSize) throws URISyntaxException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = getCommonHttpPost(pageNum, pageSize, USER_LOW_VOLTAGE_DATA);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        try {
            return this.parseTotalNum(EntityUtils.toString(entity, "UTF-8"));
        } catch (Exception e) {
            log.error("getRealTimePowerOutageTotalNum error", e);
            return 0;
        } finally {
            response.close();
            httpClient.close();
        }
    }

    public List<RealTimePowerOutage> getRealTimePowerOutage(String pageNum, String pageSize) throws URISyntaxException, IOException {
        String url = REAL_TIME_POWER_OUTAGE + "?pageSize=" + pageSize + "&pageNum=" + pageNum + "&org_no=43402&org_lev=5&APPCODE=afda03b72ebc4769b3aef4bfad7f3fee";
        HttpRequest request = HttpUtil.createGet(url)
                .header("Authorization", "APPCODE afda03b72ebc4769b3aef4bfad7f3fee");
        String body = request.execute().body();
        try {
            return this.parseData(body, RealTimePowerOutage.class);
        } catch (Exception e) {
            log.error("getRealTimePowerOutage error", e);
            return new ArrayList<>();
        }
    }

    public Integer getGridTgPowerDfTotalNum(String pageNum, String pageSize) throws URISyntaxException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = getCommonHttpPost(pageNum, pageSize, REAL_TIME_POWER_TEST);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        try {
            return this.parseTotalNum(EntityUtils.toString(entity, "UTF-8"));
        } catch (Exception e) {
            log.error("getRealTimePowerOutageTotalNum error", e);
            return 0;
        } finally {
            response.close();
            httpClient.close();
        }
    }

    public List<RdsGridTgPowerDf> getGridTgPowerDf(String pageNum, String pageSize) throws URISyntaxException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = getCommonHttpPost(pageNum, pageSize, REAL_TIME_POWER_TEST);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        try {
            return this.parseData(EntityUtils.toString(entity, "UTF-8"), RdsGridTgPowerDf.class);
        } catch (Exception e) {
            log.error("getGridTgPowerDf error", e);
            return new ArrayList<>();
        } finally {
            response.close();
            httpClient.close();
        }
    }


    public Integer getGridTgVoltDfTotalNum(String pageNum, String pageSize) throws URISyntaxException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = getCommonHttpPost(pageNum, pageSize, REAL_TIME_POWER_VOLT_TEST);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        try {
            return this.parseTotalNum(EntityUtils.toString(entity, "UTF-8"));
        } catch (Exception e) {
            log.error("getRealTimePowerOutageTotalNum error", e);
            return 0;
        } finally {
            response.close();
            httpClient.close();
        }
    }

    public List<RdsGridTgVoltDf> getGridTgVoltDf(String pageNum, String pageSize) throws URISyntaxException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = getCommonHttpPost(pageNum, pageSize, REAL_TIME_POWER_VOLT_TEST);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        try {
            return this.parseData(EntityUtils.toString(entity, "UTF-8"), RdsGridTgVoltDf.class);
        } catch (Exception e) {
            log.error("getGridTgPowerDf error", e);
            return new ArrayList<>();
        } finally {
            response.close();
            httpClient.close();
        }
    }


    public Integer getGridTgCurDfTotalNum(String pageNum, String pageSize) throws URISyntaxException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = getCommonHttpPost(pageNum, pageSize, REAL_TIME_CUR_VOLT);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        try {
            return this.parseTotalNum(EntityUtils.toString(entity, "UTF-8"));
        } catch (Exception e) {
            log.error("getRealTimePowerOutageTotalNum error", e);
            return 0;
        } finally {
            response.close();
            httpClient.close();
        }
    }

    public List<RdsGridTgCurDf> getGridTgCurDf(String pageNum, String pageSize) throws URISyntaxException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = getCommonHttpPost(pageNum, pageSize, REAL_TIME_CUR_VOLT);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        try {
            return this.parseData(EntityUtils.toString(entity, "UTF-8"), RdsGridTgCurDf.class);
        } catch (Exception e) {
            log.error("getGridTgPowerDf error", e);
            return new ArrayList<>();
        } finally {
            response.close();
            httpClient.close();
        }
    }


    private HttpPost getCommonHttpPost(String pageNum, String pageSize, String url) throws URISyntaxException {
        URIBuilder uri = new URIBuilder(url);
        uri.addParameter("pageSize", pageSize);
        uri.addParameter("pageNum", pageNum);
        HttpPost httpPost = new HttpPost(uri.build());
        return httpPost;
    }


    public Integer getRealTimePowerOutageTotalNum() throws URISyntaxException, IOException {
        String url = REAL_TIME_POWER_OUTAGE + "?APPCODE=afda03b72ebc4769b3aef4bfad7f3fee&pageNum=1&pageSize=10&org_no=43402&org_lev=5";
        try {
            HttpRequest request = HttpUtil.createGet(url)
                    .header("Authorization", "APPCODE afda03b72ebc4769b3aef4bfad7f3fee");
            String body = request.execute().body();
            return this.parseTotalNum(body);
        } catch (Exception e) {
            log.error("getRealTimePowerOutageTotalNum error", e);
            return 0;
        }
    }

    public Integer getRealTimePowerOutageUserTotalNum(String tgNo) throws URISyntaxException, IOException {
        String url = REAL_TIME_POWER_OUTEAGE_USER + "?APPCODE=afda03b72ebc4769b3aef4bfad7f3fee&tg_no=" + tgNo + "&pageNum=1&pageSize=10";
        try {
            HttpRequest request = HttpUtil.createGet(url)
                    .header("Authorization", "APPCODE afda03b72ebc4769b3aef4bfad7f3fee");
            String body = request.execute().body();
            return this.parseTotalNum(body);
        } catch (Exception e) {
            log.error("getRealTimePowerOutageUserTotalNum error", e);
            return 0;
        }
    }

    public List<RealTimePowerOutageUser> getRealTimePowerOutageUser(String pageNum, String pageSize, String tgNo) throws IOException {
        HttpRequest request = HttpUtil.createGet(REAL_TIME_POWER_OUTEAGE_USER + "?APPCODE=afda03b72ebc4769b3aef4bfad7f3fee&tg_no=" + tgNo + "&pageNum=" + pageNum + "&pageSize=" + pageSize)
                .header("Authorization", "APPCODE afda03b72ebc4769b3aef4bfad7f3fee");
        String body = request.execute().body();
        try {
            return this.parseData(body, RealTimePowerOutageUser.class);
        } catch (Exception e) {
            log.error("getRealTimePowerOutageUser error", e);
            return new ArrayList<>();
        }
    }


    public <T> List<T> parseData(String str, Class<T> clazz) {
        JSONObject result = JSONObject.parseObject(str);
        if (result.getInteger("errCode") == 0) {
            JSONObject data = result.getJSONObject("data");
            JSONArray jsonArray = data.getJSONArray("rows");
            return jsonArray.toJavaList(clazz);
        } else {
            log.error("获取数据异常:{}", result.getString("errMsg"));
            return new ArrayList<>();
        }
    }


    public Integer parseTotalNum(String str) {
        JSONObject result = JSONObject.parseObject(str);
        if (result.getInteger("errCode") == 0) {
            JSONObject data = result.getJSONObject("data");
            return data.getInteger("totalNum");
        } else {
            log.error("获取数据异常:{}", result.getString("errMsg"));
            return 0;
        }

    }
}
